﻿using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;

using BLL;
using ExcelLibrary.SpreadSheet;
using Model;
using Utility;

namespace EvaluationSystem
{
    public partial class DimensionList : System.Web.UI.Page
    {
        private const int D_MAX_DISPLAY_LENGTH = 30;

        protected void Page_Load(object sender, EventArgs e)
        {
            ((SiteSystemMaster)Master).InitMenu();
            ((SiteSystemMaster)Master).li3.Attributes.Add("class", "hover ccc");
            ((SiteSystemMaster)Master).b_hmenu1.Style.Add("display", "none");
            ((SiteSystemMaster)Master).b_hmenu2.Style.Add("display", "none");
            ((SiteSystemMaster)Master).b_hmenu3.Style.Clear();
            ((SiteSystemMaster)Master).s_menu3_1.Style.Add("COLOR", "#147ab8");
            ((SiteSystemMaster)Master).s_menu3_1.Style.Add("TEXT-DECORATION", "none"); 

            /*判断是否是管理员身份*/
            if (Session["username"] == null)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "<script>alert('请先登录系统!');top.location.href='../System/Login.aspx';</script>");
                return;
            }
            else
            {
                if (!IsPostBack)
                {
                    DimensionBLL temp = new DimensionBLL();
                    DataSet ds = temp.GetDimensionAll();
                    grVDimensionManage.DataSource = ds.Tables[0].DefaultView;
                    grVDimensionManage.DataSourceID = null;
                    grVDimensionManage.DataBind();
                    temp = null;
                }
                this.btnImport.Attributes.Add("onclick", "return CheckConfirm();");
            }
        }

        protected void GridView1_Index(object sender,GridViewPageEventArgs e)
        {
            grVDimensionManage.PageIndex = e.NewPageIndex;
            DimensionBLL temp = new DimensionBLL();
            DataSet ds = temp.GetDimensionAll();
            grVDimensionManage.DataSource = ds.Tables[0].DefaultView;
            grVDimensionManage.DataSourceID = null;
            grVDimensionManage.DataBind();
            temp = null;
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
          
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int rowIndex = Int32.Parse(e.CommandArgument.ToString());//获取点击了第几行
            int dimension_id = 0;
            
            ArrayList arUNSelList = new ArrayList();

            if (e.CommandName == "Export")
            {
                //导出到Excel
                DimensionBLL temp = new DimensionBLL();
                DataSet ds = temp.GetDimensionAllReport();
      
                //记录没有选中的维度
                for(int i=0; i< ds.Tables[0].Rows.Count;i++)
                {
                    dimension_id = Int32.Parse(ds.Tables[0].Rows[i][0].ToString());

                    foreach (GridViewRow gr in grVDimensionManage.Rows)
                    {
                        if (int.Parse(grVDimensionManage.DataKeys[gr.RowIndex].Values[0].ToString().Trim()) == dimension_id)
                        {
                            CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                            if (false == chk.Checked)
                            {
                                arUNSelList.Add(dimension_id);
                                break;
                            }
                        }
                    }                    
                }

                //删除没有选中的维度
                for (int j = 0; j < arUNSelList.Count; j++)
                {
                    deleteDataRow(arUNSelList[j].ToString(), ds.Tables[0]);
                }

                //开始导出
                //ds.Tables[0].Columns.Add("最后修改时间", Type.GetType("System.DateTime"));
                //ds.Tables[0].Columns["最后修改时间"].SetOrdinal(8);

                string filePath = Server.MapPath("../userfiles") + @"\dimension_" + DateTime.Now.ToString("yyyyMMdd_HH_mm_ss") + ".xls";
                string fileName = Path.GetFileName(filePath);
                ExcelLibrary.DataSetHelper.CreateWorkbook(filePath, ds);
                Stream stream = null;
                stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                long bytesToRead = stream.Length;
                Response.Clear();
                Response.ContentType = "application/ms-excel";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);

                while (bytesToRead > 0)
                {
                    if (Response.IsClientConnected)
                    {
                        byte[] buffer = new Byte[10000];
                        int length = stream.Read(buffer, 0, 10000);
                        Response.OutputStream.Write(buffer, 0, length);
                        Response.Flush();
                        bytesToRead = bytesToRead - length;
                    }
                    else
                    {
                        bytesToRead = -1;
                    }
                }
            }
        }

        //循环删除表中的行
        protected void deleteDataRow(string dimID, DataTable dt)
        {
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                if (dt.Rows[i][0].ToString().Equals(dimID))
                {
                    dt.Rows.RemoveAt(i);
                }
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            DimensionBLL temp = new DimensionBLL();
            int selectCount = 0;
            int dimension_id = 0;

            foreach (GridViewRow gr in grVDimensionManage.Rows)
            {
                CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                if (chk.Checked)
                {
                    dimension_id = int.Parse(grVDimensionManage.
                        DataKeys[gr.RowIndex].Values[0].ToString().Trim());
                    temp.Delete(dimension_id);
                    selectCount++;
                }
            }

            if (0 == selectCount)
            {
                MessageBox.Show("您好，请至少选择一个维度");
            }

            temp = null;
            Response.Redirect(Request.Url.ToString());
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/System/AddDimension.aspx");
        }

        protected void CB_SelectAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < grVDimensionManage.Rows.Count; i++)
            {
                GridViewRow gr = grVDimensionManage.Rows[i];
                CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                chk.Checked = this.CB_SelectAll.Checked; //跟随全选按扭的状态变化;
            }
        }

        protected void grVDimensionManage_DataBound(object sender, EventArgs e)
        {
            foreach (GridViewRow gvr in grVDimensionManage.Rows)
            {
                string qTitle = gvr.Cells[4].Text.Trim();//如果题干内容过长，则进行截取。
                if (!string.IsNullOrEmpty(qTitle) && qTitle.Length > D_MAX_DISPLAY_LENGTH)
                {
                    gvr.Cells[4].Text = qTitle.Substring(0, D_MAX_DISPLAY_LENGTH) + "...";
                }
            }
        }


        protected void btnImport_Click(object sender, EventArgs e)
        {
            MessageBox.ShowConfirm(this.FileUploadTM, "是否继续?");
            //导入选中的维度
            ArrayList arSelDimList = new ArrayList();
            int dimension_id = 0;
            foreach (GridViewRow gr in grVDimensionManage.Rows)
            {
                CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                if (chk.Checked)
                {
                    dimension_id = int.Parse(grVDimensionManage.
                        DataKeys[gr.RowIndex].Values[0].ToString().Trim());
                    arSelDimList.Add(dimension_id);
                }
            }

            Boolean fileIsOK = false;
            string path = Server.MapPath("~/userfiles/");

            if (FileUploadTM.HasFile)
            {
                string fileExtension = System.IO.Path.GetExtension(FileUploadTM.FileName).ToLower();
                string[] allowExtension = { ".xls" };

                for (int i = 0; i < allowExtension.Length; i++)
                {
                    if (fileExtension == allowExtension[i])
                    {
                        fileIsOK = true;
                        break;
                    }
                }
                //Check file size < 10M
                if (FileUploadTM.PostedFile.ContentLength > 10240000)
                {
                    fileIsOK = false;
                }

                //Result
                if (fileIsOK)
                {
                    try
                    {
                        FileUploadTM.PostedFile.SaveAs(path + FileUploadTM.FileName);
                        bool b = ImportQuestion(path + FileUploadTM.FileName, arSelDimList);
                        if (true == b)
                        {
                            MessageBox.ShowAndRedirect(this, "题目导入成功", "DimensionList.aspx");
                        }
                        else
                        {
                            MessageBox.ShowAndRedirect(this, "题目导入失败", "DimensionList.aspx");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.ShowAndRedirect(this, "题目导入失败:" + ex.Message, "DimensionList.aspx");
                    }
                }
                else
                {
                    MessageBox.ShowAndRedirect(this, "文件格式错误", "DimensionList.aspx");
                }
            }
        }


        private bool ImportQuestion(string xlsFileNm,ArrayList arDimID)
        {
            try
            {
                if (!File.Exists(xlsFileNm)) return false;

                Workbook book = Workbook.Load(xlsFileNm);

                DimensionBLL dimBLL = new DimensionBLL();
                QuestionBLL qesBLL = new QuestionBLL();
                Question question = new Question();

                DataSet dimDS = dimBLL.GetDimensionAll();

                //qesBLL.DeleteAllQuestion();
                for (int k = 0; k < arDimID.Count; k++)
                {
                    qesBLL.DeleteQuestionByDim(Int32.Parse(arDimID[k].ToString()));
                }

                string dName = string.Empty;
                for (int i = 0; i < arDimID.Count; i++)
                {
                    dName = dimBLL.GetDimension(arDimID[i].ToString()).Dimnm;

                    foreach (Worksheet sheet in book.Worksheets)
                    {
                        string sheetNm = sheet.Name.Trim();

                        if (sheetNm.Equals("说明"))
                        {
                            continue;
                        }

                        if (false == sheetNm.Equals(dName))
                        {
                            continue;
                        }                        

                        int dimID = -1;//在这里加断点可以监视单个维度的导入情况

                        foreach (DataRow row in dimDS.Tables[0].Rows)
                        {
                            if (row["dimension_name"].ToString().Equals(sheetNm))
                            {
                                dimID = Int32.Parse(row["dimension_id"].ToString().Trim());
                                break;
                            }
                        }

                        if (dimID < 1)
                        {
                            string msg = "Excel工作表中存在的[" + sheet.Name + "]维度在系统维度表中不存在!"
                                + Environment.NewLine + "请先确保Excel工作表中的维度名称在系统中存在，然后再执行导入操作";
                            //Response.Write("<script>...alert('" + msg + "')</script>");
                            MessageBox.ShowMessage(msg);
                            continue;
                        }

                        for (int rowIndex = sheet.Cells.FirstRowIndex + 2;//忽略第一行(标题行)
                                rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
                        {
                            Row row = sheet.Cells.GetRow(rowIndex);

                            question.Question_no = Int32.Parse(row.GetCell(0).StringValue.Trim());
                            question.Question_title = row.GetCell(5).StringValue.Trim();
                            question.Question_answer_A = row.GetCell(6).StringValue.Trim();
                            question.Question_answer_B = row.GetCell(7).StringValue.Trim();
                            question.Question_answer_C = row.GetCell(8).StringValue.Trim();
                            question.Question_answer_D = row.GetCell(9).StringValue.Trim();
                            question.Question_answer_E = row.GetCell(10).StringValue.Trim();

                            question.Question_answer_A_score = row.GetCell(11).StringValue.Trim().Equals(string.Empty) ? 0 : Int32.Parse(row.GetCell(11).StringValue.Trim());
                            question.Question_answer_B_score = row.GetCell(12).StringValue.Trim().Equals(string.Empty) ? 0 : Int32.Parse(row.GetCell(12).StringValue.Trim());
                            question.Question_answer_C_score = row.GetCell(13).StringValue.Trim().Equals(string.Empty) ? 0 : Int32.Parse(row.GetCell(13).StringValue.Trim());
                            question.Question_answer_D_score = row.GetCell(14).StringValue.Trim().Equals(string.Empty) ? 0 : Int32.Parse(row.GetCell(14).StringValue.Trim());
                            question.Question_answer_E_score = row.GetCell(15).StringValue.Trim().Equals(string.Empty) ? 0 : Int32.Parse(row.GetCell(15).StringValue.Trim());

                            question.Question_typeid = 1;//1 单选
                            question.Question_status = 1;//1 有效

                            if (dimID > 0)
                            {
                                question.Question_dimensionid = dimID;
                            }
                            else
                            {
                                break;
                            }

                            qesBLL.Add(question);
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                string errMsg = ex.Message;
                return false;
            }
        }

    }
}